#include "novelservice.h"
#include <QFileInfo>
#include <QCryptographicHash>
#include <QThread>

//QT调用的构造函数
NovelService::NovelService(QObject *parent)
        : QObject(parent),
          m_novel_dao(new NovelDao(this)),
          m_chapter_dao(new ChapterDao(this)) {

}

//无参构造函数
NovelService::~NovelService() {

}

// 查询小说列表所有小说
QList<QObject *> NovelService::getAllNovels() {
    return m_novel_dao->findAll();
}

// 查询小说章节列表
QList<QObject *> NovelService::getChaptersByNovelId(const QString &novelId) {
    qDebug() << "查询小说的章节目录，小说编号：" << novelId;
    return m_chapter_dao->getByNovelId(novelId);
}

//导入小说
void NovelService::importFromPath(const QString &filePath) {
    // 解析小说基本信息
    NovelInfo *novelInfo = parseNovelBasicInfo(filePath);
    if (!novelInfo) {
        emit importError("解析小说基本信息失败");
        return;
    }

    //查询小说是否存在
    int count = m_novel_dao->queryCount({novelInfo->getId()});
    bool upsert;
    if (count == 0) {
        upsert = m_novel_dao->insert(novelInfo);
    } else {
        novelInfo->setUpdateTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        upsert = m_novel_dao->update(novelInfo);
    }

    if (!upsert) {
        emit importError("保存/更新小说信息失败");
        return;
    }


    //获取小说id与名字
    QString novelId = novelInfo->getId();
    QString novelName = novelInfo->getTitle();
    delete novelInfo;

    //触发导入完成信号
    emit novelImported(novelName);

    //开启后台线程
    QThread *parseThread = new QThread();
    NovelParseWorker *worker = new NovelParseWorker(m_novel_dao, m_chapter_dao);
    worker->moveToThread(parseThread);

    //创建线程与工作类的关联
    connect(parseThread, &QThread::started, [=]() {
        worker->parseNovel(filePath, novelId);
    });

    //开始线程
    parseThread->start();

}


//解析小说基本基本信息
NovelInfo *NovelService::parseNovelBasicInfo(const QString &filePath) {
    // 判断路径是否存在
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists() || !fileInfo.isFile()) {
        qWarning() << "解析小说基本信息失败，路径不存在：" << filePath;
        return nullptr;
    }

    NovelInfo *novelInfo = new NovelInfo();

    //生成小说id
    QString novelId = MD5Util::calculateMD5(filePath);
    if (novelId.isEmpty()) {
        qWarning() << "无法计算文件MD5，使用文件路径替代:" << filePath;
    }

    novelInfo->setId(novelId);
    novelInfo->setTitle(fileInfo.fileName().left(fileInfo.fileName().lastIndexOf('.')));
    novelInfo->setAuthor("未知作者");
    novelInfo->setLanguage("zh");
    novelInfo->setStatus(0);
    novelInfo->setDescription(novelInfo->getAuthor());
    novelInfo->setFileSize(fileInfo.size());
    novelInfo->setSourceType(0);
    novelInfo->setSourceUrl(fileInfo.filePath());
    novelInfo->setCreateTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    novelInfo->setUpdateTime(novelInfo->getCreateTime());

    return novelInfo;
}
